import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from config import result_bucket
from aws_model.athena_submit import submit
from sql_lambda.delete import delete_data
from base_class.inspect_logging import print_to_log
import datetime
import json
from aws_model.aws_stepfunc import send_task_success, send_task_failure


def result_gzyzx(event):
    date = event.get('p_date')
    if not date:
        date = datetime.datetime.today().strftime('%Y-%m-%d')
    table_name = sys._getframe().f_code.co_name
    month = date[0:7]
    delete_data(result_bucket,table_name, date)
    sql = f'''insert into fridge_biz_result.result_gzyzx
                (
                     select
                        t1.model as model,
                        count(distinct sn) as find_num,
                        count(distinct t2.zzfld00000b) as kyd_num,
                        format_datetime(cast ('{date}' as date) - interval '1' month,'yyyy-MM') as time
                     from
                        (
                        select
                            sn,upper(model) as model,p_date
                        from
                            dws.find_error
                        where
                            substr(p_date,1,7) = format_datetime(cast ('{date}' as date) - interval '1' month,'yyyy-MM')
                        ) t1
                     left join
                         (
                        select
                            zzfld00000b,objectid,p_date
                        from
                            ods.kyd_ods
                        where
                            gzdl != '用户体验' and gzdl != '安装' and
                            gzdl != '保养' and gzdl != '搁板（架）' and
                            gzdl != '果抽框' and gzdl != '鉴定' and
                            gzdl != '门体外部' and gzdl != '门体内部' and
                            gzdl != '外观缺陷' and gzdl != '调试' and
                            gzdl != '噪音' and gzdl != '异味' and
                            gzdl != '结构件'
                        and
                            zzfld000001 = 'QT30'
                         ) t2
                     on
                        t1.sn = t2.zzfld00000b
                     and
                        t1.p_date <= cast((date(t2.p_date) + interval '3' month) as varchar)
                     and
                        t1.p_date >= cast((date(t2.p_date) - interval '3' month) as varchar)
                     group by
                        t1.model
)'''

    athena_response = submit(sql)
    print_to_log("athena_response: ", athena_response)
    output = {"msg": f"{table_name} submit ok", "Payload": {}}
    output = json.dumps(output)
    step_response = send_task_success(tasktoken, output)
    print_to_log("step_response: ", step_response)


if __name__ == '__main__':
    try:
        event = json.loads(sys.argv[1])
        tasktoken = event.get('TaskToken')
        result_gzyzx(event)
    except Exception as e:
        print_to_log("athena_submit 失败")
        print_to_log("原因： ", str(e))
        send_task_failure(str(e), f'执行{sys._getframe().f_code.co_filename}错误', tasktoken)

